using System;
using System.Collections.Generic;
using Microsoft.SharePoint;
using System.Linq;

namespace SharePoint.DataMapper
{
	[FieldMapper(typeof(SPFieldUser), SPFieldType.User)]
	public class FieldUserMapper : FieldMapper
	{
		protected override SPField AddFieldInternal(ListDataContext context, SPFieldCollection collection, Type propertyType, FieldAttribute attribute)
		{
			SPFieldUser field = (SPFieldUser)base.AddFieldInternal(context, collection, propertyType, attribute);
			field.AllowMultipleValues = attribute.AllowMultipleValues;
			field.SelectionMode = attribute.UserSelectionMode;
			field.Presence = true;
			return field;
		}

		protected override FieldAttribute GetFieldAttributeInternal(SPField field)
		{
			FieldAttribute attribute = base.GetFieldAttributeInternal(field);

			SPFieldUser fieldUser = field as SPFieldUser;
			if (fieldUser == null)
			{
				return attribute;
			}
			attribute.AllowMultipleValues = fieldUser.AllowMultipleValues;
			attribute.UserSelectionMode = fieldUser.SelectionMode;
			return attribute;
		}

		protected override object SetFieldInternal(ListDataContext context, object value, Type propertyType)
		{
			if (value is SPFieldUserValue)
			{
				return value;
			}
			if (value is SPFieldUserValueCollection)
			{
				return value;
			}
			if (value is SPUser)
			{
				SPUser user = (SPUser)value;
				return new SPFieldUserValue(context.Web, user.ID, user.Name);
			}
			if (value is IList<SPUser>)
			{
				SPFieldUserValueCollection userValues = new SPFieldUserValueCollection();
				IList<SPUser> list = (IList<SPUser>)value;
				foreach (SPUser user in list)
				{
					userValues.Add(new SPFieldUserValue(context.Web, user.ID, user.Name));
				}
				return userValues;
			}
			return null;
		}

		protected override object GetFieldInternal(ListDataContext context, object value, Type propertyType)
		{
			SPFieldUserValueCollection userValues = (value is SPFieldUserValueCollection) ? (SPFieldUserValueCollection)value : new SPFieldUserValueCollection(context.Web, value.ToString());
			if (typeof(SPFieldUserValueCollection) == propertyType)
			{
				return userValues;
			}
			if (typeof(SPFieldUserValue) == propertyType)
			{
				return userValues.FirstOrDefault();
			}
			if (typeof(SPUser) == propertyType)
			{
				SPFieldUserValue userValue = userValues.FirstOrDefault();
				if (userValue != null)
				{
					return userValue.User;
				}
			}
			if (typeof(IList<SPUser>).IsAssignableFrom(propertyType))
			{
				IList<SPUser> list = (IList<SPUser>)Activator.CreateInstance(propertyType);
				foreach (SPFieldUserValue userValue in userValues)
				{
					list.Add(userValue.User);
				}
				return list;
			}
			return null;
		}
	}
}